<template>
  <view class='recommend'>
    <!--    <block v-if="tempArr.length">-->
    <!-- 标题和更多按钮 -->
    <view class="course-header">
      <text class="course-title">为您推荐</text>
      <view class="more-btn" @click="jumpRecommended">
        <text>更多</text>
        <image class="more" :src="IMAGE_CONFIG.more"></image>
        <!--        <u-icon name="arrow-right" size="18" color="#999"></u-icon>-->
      </view>
    </view>
    <!-- 瀑布流内容区 -->
    <view class="waterfall-grid">
      <view
          class="course-card"
          v-for="(course, index) in tempArr"
          :key="course.id"
          :style="{ animationDelay: `${index * 0.1}s` }"
      >
        <!-- 课程图片 -->
        <view class="card-image-container" @click="jumpDetails(course.id)">
          <image
              :src="course.image"
              mode="aspectFill"
              lazy-load
              class="card-image"
          ></image>
          <view class="course-type-tag" :class="course.productValue['默认'].type === 0 ? 'offline' : 'online'">
            <image class="type-icon" :src="course.productValue['默认'].type === 0 ? IMAGE_CONFIG.xianXia : IMAGE_CONFIG.xianShang"></image>
            <text class="type-text">{{ course.productValue['默认'].type === 0 ? '线下课' : '线上课' }}</text>
          </view>
        </view>

        <!-- 课程信息 -->
        <view class="card-info">
          <view class="row">
            <text class="course-title" @click="jumpDetails(course.id)">{{ course.name }}</text>
            <text class="course-age" @click="jumpDetails(course.id)">{{ course.ageRange }}</text>
          </view>
          <view class="row">
            <view class="original-price" @click="jumpDetails(course.id)">¥{{ course.otPrice }}/课时</view>
            <view class="provider" @click="jumpDetails(course.id)">{{ course.merName }}</view>
          </view>
          <view class="freely" @click="goBuy(course)">
            <view>限时优惠</view>
            <view>¥{{ course.price }}</view>
            <!-- <view>免费</view> -->
          </view>
        </view>
      </view>
    </view>
    <!--    </block>-->
  </view>
</template>

<script>
import {mapGetters} from "vuex";
import {getProductHot} from '@/api/product.js';

import {toLogin} from "@/libs/login.js";

import {Debounce} from "@/utils/validate.js";
import {postCartAdd} from "@/api/product";
import {onGetPreOrder} from "@/libs/order";
import {ProductMarketingTypeEnum,} from "@/enums/productEnums";
import {IMAGE_CONFIG} from '@/utils/imageConfig'

let app = getApp();
export default {
  name: 'recommend',
  components: {},
  props: {
    categoryId: {
      type: Number,
      default: function () {
        return 0;
      }
    },
  },
  data() {
    return {
      IMAGE_CONFIG: IMAGE_CONFIG.index,
      urlDomain: this.$Cache.get("imgHost"),
      theme: app.globalData.theme,
      params: { //精品推荐分页
        page: 1,
        limit: 4,
        cid: 0,
        lng: '',
        lat: ''
      },
      loading: false,
      tempArr: [],
      currentCategory: 'all',
      courseList: [],
      gridColumns: 2, // 瀑布流列数
      gridGap: 16,    // 网格间距(rpx)
      productValue: [], //系统属性
      attrValue: "", //已选属性
      attr: {
        cartAttr: false,
        productAttr: [],
        productSelect: {},
      },
      productInfo: {},
      id: '',
    };
  },
  watch: {
    categoryId: function (val) { //监听props中的属性
      this.tempArr = [];
      this.get_host_product()
    }
  },
  // onShow() {
  //   this.tempArr = [];
  //   this.get_host_product();
  // },
  mounted() {
    this.tempArr = [];
    this.get_host_product();
  },

  computed: {
    ...mapGetters(["isLogin", 'uid']),
    // 计算网格列宽
    columnWidth() {
      const screenWidth = uni.getSystemInfoSync().windowWidth;
      return (screenWidth - (this.gridColumns + 1) * this.gridGap) / this.gridColumns;
    },
  },
  methods: {
    jumpRecommended() {
      uni.navigateTo({
        // url: '/pages/goods/lecturer/index'
        url: '/pages/goods/goods_list/index'
      })
    },
    /**
     * 获取我的推荐
     */
    get_host_product() {
      this.params.cid = this.categoryId;
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.params.lng = res.longitude;
          this.params.lat = res.latitude;
          getProductHot(
              this.params
          ).then((res) => {
            this.tempArr = res.data.list
          }).catch(err => {
            console.log(err)
          });
          console.log('获取位置成功:', res.longitude, res.latitude);
        },
        fail: (err) => {
          console.log('获取位置失败:', err);
          // 获取失败时设置默认值或保持为空
          this.params.lng = '';
          this.params.lat = '';
          getProductHot(
              this.params
          ).then((res) => {
            this.tempArr = res.data.list
          }).catch(err => {
            console.log(err)
          });
        }
      });
    },
    jumpDetails(id) {
      if (this.isLogin === false) {
        toLogin();
      } else {
        uni.navigateTo({
          url: '/pages/discover/courseDetails/index?id=' + id
        })
      }
    },
    /**
     * 立即购买的按钮触发
     */
    goBuy: Debounce(function (item) {
      if(item.isBuy && item.productValue['默认'].type === 5){
        return this.$util.Tips({
          title: '线上课程只能购买一次，不能重复购买',
        });
      }
      // goBuy:(function (e) {
      if (this.isLogin === false) {
        toLogin();
      } else {
        this.productInfo = item
        this.goCat(0);
      }
    }),
    /**
     * 加入购物车
     */
    goCat: function (num) {
      let that = this,
          productSelect = that.productValue[this.attrValue];
      //打开属性
      if (that.attrValue) {
        //默认选中了属性，但是没有打开过属性弹窗还是自动打开让用户查看默认选中的属性
        that.attr.cartAttr = !that.isOpen ? true : false;
      } else {
        if (that.isOpen) that.attr.cartAttr = true;
        else that.attr.cartAttr = !that.attr.cartAttr;
      }
      //只有关闭属性弹窗时进行加入购物车
      if (that.attr.cartAttr === true && that.isOpen === false)
        return (that.isOpen = true);
      //如果有属性,没有选择,提示用户选择
      if (
          that.attr.productAttr.length &&
          productSelect.stock === 0 &&
          that.isOpen === true
      )
        return that.$util.Tips({
          title: "产品库存不足，请选择其它",
        });
      if (num === 1) {
        let q = {
          productId: parseFloat(that.id),
          cartNum: parseFloat(that.attr.productSelect.cart_num),
          isNew: false,
          productAttrUnique: that.attr.productSelect !== undefined ?
              that.attr.productSelect.unique : that.productInfo.id,
        };
        postCartAdd(q)
            .then(function (res) {
              that.isOpen = false;
              that.attr.cartAttr = false;
              that.$util.Tips({
                title: "添加购物车成功",
                success: () => {
                  that.getCartCount(true);
                },
              });
            })
            .catch((res) => {
              that.isOpen = false;
              return that.$util.Tips({
                title: res,
              });
            });
      } else {
        this.getPreOrder();
      }
    },
    /**
     * 预下单
     */
    getPreOrder: function () {
      if (
          this.marketingType === ProductMarketingTypeEnum.Groupbuying &&
          this.attr.productSelect.cart_num > this.buyLimitNum
      ) {
        this.isOpen = false;
        return this.$util.Tips({
          title: "超出限购数量",
        });
      }
      if (this.attr.productSelect.cart_num < 1) {
        uni.showToast({
          title: "单次可购买商品数量范围为 1~99",
          icon: "none",
        });
      } else {
        let types = "";
        // switch (this.marketingType) {
        switch (0) {
          case ProductMarketingTypeEnum.Normal:
            if (this.productInfo.type === 4) {
              types = "video";
            } else {
              types = "buyNow";
            }
            break;
          case ProductMarketingTypeEnum.Seckill:
            types = "seckill";
            break;
          case ProductMarketingTypeEnum.Groupbuying:
            types = "group";
            break;
        }
        this.id = this.productInfo.id ? this.productInfo.id : "";
        onGetPreOrder(types, [{
          attrValueId: parseFloat(this.productInfo.productValue['默认'].id),
          // attrValueId: parseFloat('2678'),
          productId: parseFloat(this.productInfo.id),
          // productId: parseFloat('99'),
          productNum: parseFloat('1'),
          groupBuyActivityId: parseFloat(this.groupActivityId),
          groupBuyRecordId: 0,
        },]);
      }
      this.isOpen = false;
    },
  },
}
</script>

<style scoped lang="scss">

$colorTit: #231917;
$colorContent: #53433F;

.recommend {
  padding: 15px;
  margin-top: 40rpx;

  .title {
    height: 120rpx;
    line-height: 120rpx;
    font-size: 32rpx;
    color: #333333;
  }
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 11px;

  .course-title {
    font-size: 20px;
    /*font-weight: bold;*/
    color: $colorTit;
  }

  .more-btn {
    display: flex;
    align-items: center;
    color: #8F4C38;
    font-weight: bold;

    .more {
      width: 16rpx;
      height: 24rpx;
      margin-top: 2px;
      margin-left: 12rpx;
    }
  }
}

/* 瀑布流布局 */
.waterfall-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 28rpx;
}

.course-card {
  background-color: white;
  border-radius: 12rpx;
  overflow: hidden;
  //box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
  opacity: 0;
  transform: translateY(20rpx);
  animation: fadeIn 0.5s forwards;
}

@keyframes fadeIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.card-image-container {
  position: relative;
  width: 100%;
  height: 200rpx;
}

.card-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 200rpx;
  object-fit: cover;
}

.card-info {
  padding: 16rpx 0;
}
.row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}
.course-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #222;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 12rpx;
}
.course-age {
  font-size: 24rpx;
  color: #888;
  min-width: 80rpx;
  text-align: right;
}
.original-price {
  font-size: 26rpx;
  color: #f56c6c;
  font-weight: 500;
}
.provider {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  min-width: 100rpx;
}
.freely {
  margin-top: 10rpx;
  background: linear-gradient(90deg, #f7e1b5 0%, #eac784 100%);
  border-radius: 12rpx;
  padding: 8rpx 16rpx;
  color: #8e4c38;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28rpx;
}


</style>